import io
import os
import time
from datetime import datetime

from PyPDF2 import PdfReader, PdfWriter
from openpyxl import load_workbook
from reportlab.lib.pagesizes import letter
from reportlab.lib.units import cm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas

startTime = time.time()
# 打开Excel文件
excel_file = "input_excel/" + '1.xlsx'
wb = load_workbook(excel_file)

# 获取特定的工作表，这里假设工作表名为"MySheet"
sheet_name = 'MySheet'
sheet = wb[sheet_name]


def split_text_to_lines(text, max_width, canvas, font_size):
    lines = []
    words = text
    line = ""

    for word in words:
        if canvas.stringWidth(line + word, 'SimSun', font_size) <= max_width:
            if line:
                line += word
            else:
                line = word
        else:
            lines.append(line)
            line = word

    lines.append(line)
    return lines


def create_page(text, distance_from_footer, font_size):
    # 创建一个新的 PDF，包含要添加的文本
    packet = io.BytesIO()
    can = canvas.Canvas(packet, pagesize=letter)

    # 注册一个中文字体
    pdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttc'))  # SimSun 是宋体，你可以换成其他支持的中文字体
    can.setFont('SimSun', font_size)

    # 计算文字位置
    page_width, page_height = letter
    margin = 1 * cm  # 左右页边距
    x_start = margin
    y_start = distance_from_footer * cm  # 距离页脚 distance_from_footer 厘米
    max_width = page_width - 2 * margin

    # 自动换行
    text_lines = split_text_to_lines(text, max_width, can, font_size)
    y = y_start

    for line in text_lines:
        text_width = can.stringWidth(line, 'SimSun', font_size)
        x_centered = (page_width - text_width) / 2
        can.drawString(x_centered, y, line)
        y -= 14  # 行高，可以根据字体大小调整

    can.save()

    # 移动到开始位置
    packet.seek(0)
    return PdfReader(packet)


current_directory = os.getcwd() + "/input_pdf"
# 使用os.walk遍历当前目录及其所有子目录
for root, dirs, files in os.walk(current_directory):
    for name in files:
        # 获取文件的完整路径
        full_path = os.path.join(root, name)
        print(f"文件: {full_path}")

        # 读取已存在的 PDF 文件
        existing_pdf = PdfReader(open(full_path, "rb"))
        output = PdfWriter()
        new_pdfs = {}
        # 跳过第一行，从第二行开始迭代
        print("开始创建pdf")
        new_pdf_start_time = time.time()
        for row in sheet.iter_rows(min_row=2):
            new_pdf = create_page(row[1].value, row[3].value, row[2].value)
            new_pdfs[row[0].row - 2] = new_pdf
        wb.close()
        print("创建花费时间：", time.time() - new_pdf_start_time)
        print("开始合并pdf")
        for i in range(len(existing_pdf.pages)):
            page = existing_pdf.pages[i]
            if i in new_pdfs:
                merge_start_time = time.time()
                page.merge_page(new_pdfs[i].pages[0])
                print(f"第{i+1}页完成，花费时间:{time.time() - merge_start_time}")
            output.add_page(page)
        # 保存输出 PDF
        time_str = datetime.now().strftime("%H%M%S")
        new_filename = f"{name.rsplit('.', 1)[0]}_{time_str}.{name.rsplit('.', 1)[1]}"
        print("开始写入pdf")
        output_pdf = "output_pdf/" + new_filename
        with open(output_pdf, "wb") as output_stream:
            output.write(output_stream)

print("花费时间", time.time() - startTime)
